import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { cn } from '@/utils/cn';
import { useAppStore, User } from '@/stores/appStore';
import { mockUser } from '@/data/mockData';
import { Phone, MessageCircle, User as UserIcon, Lock, Eye, EyeOff } from 'lucide-react';

export default function LoginPage() {
  const navigate = useNavigate();
  const { login, showToast } = useAppStore();
  
  const [loginMethod, setLoginMethod] = useState<'phone' | 'wechat'>('phone');
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const handlePhoneLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!phone || !code) {
      showToast('请输入手机号和验证码', 'error');
      return;
    }

    setIsLoading(true);
    // 模拟登录过程
    setTimeout(() => {
      const user: User = {
        ...mockUser,
        phone: phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
        currentChildId: mockUser.children[0]?.id || ''
      };
      login(user);
      showToast('登录成功！', 'success');
      navigate('/');
      setIsLoading(false);
    }, 1500);
  };

  const handleWechatLogin = () => {
    setIsLoading(true);
    // 模拟微信登录
    setTimeout(() => {
      const user: User = {
        ...mockUser,
        wechat: '微信用户',
        currentChildId: mockUser.children[0]?.id || ''
      };
      login(user);
      showToast('微信登录成功！', 'success');
      navigate('/');
      setIsLoading(false);
    }, 1500);
  };

  const handleSendCode = () => {
    if (!phone) {
      showToast('请输入手机号', 'error');
      return;
    }
    // 简单的手机号验证
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      showToast('请输入正确的手机号', 'error');
      return;
    }
    showToast('验证码已发送', 'success');
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-50 via-warm-50 to-secondary-50 flex items-center justify-center px-4">
      <div className="w-full max-w-md">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="w-20 h-20 bg-gradient-to-br from-accent-400 to-accent-600 rounded-full flex items-center justify-center mx-auto mb-4 shadow-lg">
            <BookIcon className="w-10 h-10 text-white" />
          </div>
          <h1 className="text-3xl font-bold text-gray-800 mb-2">欢迎回来</h1>
          <p className="text-gray-600">登录绘本岛，开启亲子阅读之旅</p>
        </div>

        {/* 登录方式切换 */}
        <div className="bg-white rounded-2xl shadow-lg p-6 mb-6">
          <div className="flex bg-gray-100 rounded-xl p-1 mb-6">
            <button
              onClick={() => setLoginMethod('phone')}
              className={cn(
                "flex-1 py-3 px-4 rounded-lg font-medium transition-all duration-200",
                loginMethod === 'phone'
                  ? "bg-white text-primary-600 shadow-sm"
                  : "text-gray-600 hover:text-gray-800"
              )}
            >
              <Phone className="w-5 h-5 inline-block mr-2" />
              手机号登录
            </button>
            <button
              onClick={() => setLoginMethod('wechat')}
              className={cn(
                "flex-1 py-3 px-4 rounded-lg font-medium transition-all duration-200",
                loginMethod === 'wechat'
                  ? "bg-white text-primary-600 shadow-sm"
                  : "text-gray-600 hover:text-gray-800"
              )}
            >
              <MessageCircle className="w-5 h-5 inline-block mr-2" />
              微信登录
            </button>
          </div>

          {/* 手机号登录表单 */}
          {loginMethod === 'phone' && (
            <form onSubmit={handlePhoneLogin} className="space-y-4">
              <div className="relative">
                <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="请输入手机号"
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500 focus:border-transparent"
                  maxLength={11}
                />
              </div>

              <div className="flex space-x-3">
                <div className="relative flex-1">
                  <MessageCircle className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    type="text"
                    value={code}
                    onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}
                    placeholder="请输入验证码"
                    className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500 focus:border-transparent"
                    maxLength={6}
                  />
                </div>
                <button
                  type="button"
                  onClick={handleSendCode}
                  className="px-4 py-3 bg-accent-500 hover:bg-accent-600 text-white rounded-xl font-medium transition-colors whitespace-nowrap"
                >
                  发送验证码
                </button>
              </div>

              <div className="relative">
                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type={showPassword ? "text" : "password"}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="请输入密码（可选）"
                  className="w-full pl-10 pr-12 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500 focus:border-transparent"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>

              <button
                type="submit"
                disabled={isLoading}
                className={cn(
                  "w-full py-3 bg-primary-600 hover:bg-primary-700 text-white rounded-xl font-medium transition-colors",
                  isLoading && "opacity-50 cursor-not-allowed"
                )}
              >
                {isLoading ? "登录中..." : "立即登录"}
              </button>
            </form>
          )}

          {/* 微信登录 */}
          {loginMethod === 'wechat' && (
            <div className="text-center space-y-4">
              <div className="w-32 h-32 bg-gray-100 rounded-2xl flex items-center justify-center mx-auto">
                <div className="w-20 h-20 bg-green-500 rounded-xl flex items-center justify-center">
                  <MessageCircle className="w-10 h-10 text-white" />
                </div>
              </div>
              <p className="text-gray-600">微信扫码一键登录</p>
              <button
                onClick={handleWechatLogin}
                disabled={isLoading}
                className={cn(
                  "w-full py-3 bg-green-500 hover:bg-green-600 text-white rounded-xl font-medium transition-colors",
                  isLoading && "opacity-50 cursor-not-allowed"
                )}
              >
                {isLoading ? "登录中..." : "微信一键登录"}
              </button>
            </div>
          )}
        </div>

        {/* 注册提示 */}
        <div className="text-center text-gray-600">
          <p>还没有账号？
            <button 
              onClick={() => navigate('/register')}
              className="text-primary-600 hover:text-primary-700 font-medium ml-1"
            >
              立即注册
            </button>
          </p>
        </div>
      </div>
    </div>
  );
}

// 书本图标组件
function BookIcon({ className }: { className?: string }) {
  return (
    <svg
      className={className}
      fill="currentColor"
      viewBox="0 0 24 24"
    >
      <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/>
    </svg>
  );
}